#!/Users/michael/anaconda3/bin/python

from datetime import datetime, timedelta
import requests

def get_price(url):
    headers = {'X-CoinAPI-Key' : 'E231E218-9F0D-4A4F-900F-63C45572686E'}
    response = requests.get(url, headers=headers)
    return response.json()[0]['rate_close']


def get_monthly_report(coin):
    now = datetime.now()
    now = datetime(2021, 6, 1)
    this_month = now.month
    this_year = now.year
    last_month = this_month - 1
    last_year = this_year
    if last_month == 0:
        last_month = 12
        last_year = this_year - 1
    last_day = (datetime(last_year, this_month, 1) - timedelta(days=1)).day

    start_url = 'https://rest.coinapi.io/v1/exchangerate/{coin}/USD/history?period_id=1DAY&time_start={last_year}-{last_month:02}-01T00:00:00&time_end{last_year}-{last_month:02}-02T00:00:00'
    start_url = start_url.format(coin=coin, last_year=last_year, last_month=last_month)
    start_price = get_price(start_url)

    end_url = 'https://rest.coinapi.io/v1/exchangerate/{coin}/USD/history?period_id=1DAY&time_start={last_year}-{last_month:02}-{last_day}T00:00:00&time_end={this_year}-{this_month:02}-01T00:00:00'
    end_url = end_url.format(coin=coin, last_year=last_year, last_month=last_month, this_year=this_year, this_month=this_month, last_day=last_day)
    end_price = get_price(end_url)

    change_rate = (end_price - start_price) / start_price
    report = '''
    coin: {coin}
    start_price: ${start_price} ({last_year}-{last_month:02}-01)
    end_price  : ${end_price} ({last_year}-{last_month:02}-{last_day:02})
    change_rate: {change_rate:.2f}%
    '''.format(
            coin=coin, 
            start_price=start_price, 
            end_price=end_price, 
            last_year=last_year,
            last_month=last_month,
            last_day=last_day,
            change_rate=change_rate * 100
        )
    print(report)
    return (coin, start_price, end_price)
    


if __name__ == '__main__':
    for_input = []
    for coin in ['BTC', 'ETH', 'FTM', 'THETA', 'DOGE', 'ICP']:
        coin, start_price, end_price = get_monthly_report(coin)
        for_input.append(' '.join([coin, str(start_price), str(end_price)]))
    print(', '.join(for_input))


